<?php
	//DataLog class
	class DataLog {
		private $datalog_id;
		private $user_id;
		private $datalog_type_id;
		private $datalog_value;
		private $datalog_unit;
		private $datalog_note;
		private $datalog_time;
		
		//Note: Constructor does not set ID however insert() and DataLog::createDataLog() sets ID
		//      Use DataLog::createDataLog() for manipulation of DataLog
		
		//Constructor for DataLog
		//
		//Param: user id, type id, value, unit, note, time
		function __construct($user_id, $datalog_type_id, $datalog_value, $datalog_unit, $datalog_note, $datalog_time = null) {
			$this->setUserID($user_id);
			$this->setTypeID($datalog_type_id);
			$this->setValue($datalog_value);
			$this->setUnit($datalog_unit);
			$this->setNote($datalog_note);
			$this->setTime($datalog_time);
		}
		
		//Setter for DataLog ID
		function setDatalogID($val) {
			$this->datalog_id = $val;
		}
		//Getter for DataLog ID
		function getDatalogID() {
			return $this->datalog_id;
		}
		
		//Setter for User ID
		function setUserID($val) {
			$this->user_id = $val;
		}
		//Getter for User ID
		function getUserID() {
			return $this->user_id;
		}
		
		//Setter for DataLog Type ID
		function setTypeID($val) {
			$this->datalog_type_id = $val;
		}
		//Getter for DataLog Type ID
		function getTypeID() {
			return $this->datalog_type_id;
		}
		
		//Setter for DataLog value
		function setValue($val) {
			$this->datalog_value = $val;
		}
		//Getter for DataLog value
		function getValue() {
			return $this->datalog_value;
		}		
		
		//Setter for DataLog unit
		function setUnit($val) {
			$this->datalog_unit = $val;
		}
		//Getter for DataLog unit
		function getUnit() {
			return $this->datalog_unit;
		}
		
		//Setter for DataLog note
		function setNote($val) {
			$this->datalog_note = $val;
		}
		//Getter for DataLog note
		function getNote() {
			return $this->datalog_note;
		}
		
		//Setter for DataLog time
		function setTime($val = null) {
			if ($val === null) {
				$this->datalog_time = date(DATE_FORMAT);
			} else {
				$this->datalog_time = $val;
			}
		}					
		//Getter for DataLog time
		function getTime() {
			return $this->datalog_time;
		}
		
		//Insert new DataLog info into database
		//Sets DataLog ID to current DataLog
		//
		//Return: DataLog ID or O
		function insert() {
			$db = Database::get();
			$query = "INSERT INTO " . DATALOG_TABLE . " 
				(user_id, datalog_type_id, datalog_value, datalog_unit, datalog_note, created_at)
				VALUES(?, ?, ?, ?, ?, ?);";
			$stmt = $db->prepare($query);
			if ($stmt) {

				$user_id = $this->getUserID();
				$datalog_type_id = $this->getTypeID();
				$datalog_value = $this->getValue();
				$datalog_unit = $this->getUnit();
				$datalog_note = $this->getNote();
				$datalog_time = $this->getTime();
								
				$stmt->bind_param("ddssss", $user_id, $datalog_type_id, $datalog_value, $datalog_unit, $datalog_note, $datalog_time);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$datalog_id = $stmt->insert_id;
				$this->setDatalogID($datalog_id);
				$stmt->close();
				
				//Create notification for the doctor to input into database
				$notification_message = str_replace('PERSON', User::findName($user_id), LOG_DOCTOR_MSG);
				$notification_message = str_replace('TYPE', DataLog::findTypeName($datalog_type_id), $notification_message);
				$notification_message = str_replace('VALUE', $datalog_value, $notification_message);
				$notification_type_id = Notification::findTypeID('log_doctor');

				$doctor_list = Patient::doctorList($user_id);
				if ($doctor_list !== null) {
					foreach ($doctor_list as $doctor) {			
						$doctor_id = $doctor['doctor_id'];
						if (Patient::checkDoctor($doctor_id, $user_id)) {
							$notification = new Notification($doctor_id, $notification_type_id, $notification_message, $user_id, $datalog_id, $datalog_time);
							$notification->insert();
						}
					}
				}
				
				return intval($datalog_id);
				
			}
			return 0;
		}
		
		//Remove DataLog from database
		//
		//Return: true or false
		function remove() {
			$db = Database::get();
			$query = "DELETE FROM " . DATALOG_TABLE . " 
				WHERE datalog_id = ?;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$datalog_id = $this->getDatalogID();
				$stmt->bind_param("d", $datalog_id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$stmt->close();
				
				//Create notification for the doctor to delete from database
				$user_id = $this->getUserID();
				$doctor_list = Patient::doctorList($user_id);
				
				$notification_type_id = Notification::findTypeID('log_doctor');
				$notification_time = $this->getTime();
				
				if ($doctor_list !== null) {
					foreach ($doctor_list as $doctor) {			
						$doctor_id = $doctor['doctor_id'];
						if (Patient::checkDoctor($doctor_id, $user_id)) {
							$notification_id = Notification::findIDWithLog($doctor_id, $notification_type_id, $user_id, $datalog_id);
							$notification = Notification::createNotification($notification_id);
							$notification->remove();
						}
					}
				}				
				
				return true;
			}
			return false;
		}
		
		//Create DataLog object given the ID by taking information from the database
		//Information taken from the database: user id, type id, value, unit, note, time
		//
		//Param: datalog id
		//Return: DataLog object
		static function createDataLog($id) {
			$db = Database::get();
			$query = "SELECT * FROM " . DATALOG_TABLE . "
					  WHERE datalog_id = ?;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("d", $id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$result = $stmt->get_result();
				$datalog_row = null;
				if ($row = $result->fetch_assoc()) {
					$datalog_row = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for Data Log: ' . $db->error);
			}
			
			$datalog = null;
			if ($datalog_row !== null) {
				$user_id = $datalog_row['user_id'];
				$datalog_type_id = $datalog_row['datalog_type_id'];
				$datalog_value = $datalog_row['datalog_value'];
				$datalog_unit = $datalog_row['datalog_unit'];
				$datalog_note = $datalog_row['datalog_note'];
				$datalog_time = $datalog_row['created_at'];
				
				$datalog = new DataLog($user_id, $datalog_type_id, $datalog_value, $datalog_unit, $datalog_note, $datalog_time);
				$datalog->setDatalogID($id);
				}
				
				
			return $datalog;
		}
		
		//Get list of DataLog given the user id
		//
		//Param: user id
		//Return: List of DataLog
		static function getDataLogList($user_id) {
			$db = Database::get();
			$query = "SELECT * FROM " . DATALOG_TABLE . "
					  WHERE user_id = ? ORDER BY created_at;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("d", $user_id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$result = $stmt->get_result();
				$datalog_list = null;
				while ($row = $result->fetch_assoc()) {
					$datalog_list[] = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for Data Log: ' . $db->error);
			}
			
			return $datalog_list;
		}

		//Get list of DataLog average per day, given the user id and type id
		//
		//Param: user id, type id
		//Return: List of DataLog
		static function getDataLogListForTypePerDay($user_id, $datalog_type_id) {
			$db = Database::get();
			$query = "SELECT DATE(created_at) as datalog_date, AVG(datalog_value) as datalog_sum FROM " . DATALOG_TABLE . "
					  WHERE user_id = ? AND datalog_type_id = ?
					  GROUP BY DATE(created_at);";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("dd", $user_id, $datalog_type_id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$result = $stmt->get_result();
				$datalog_list = null;
				while ($row = $result->fetch_assoc()) {
					$datalog_list[] = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for Data Log: ' . $db->error);
			}
			
			return $datalog_list;
		}		
		
		//Get list of DataLog type
		//
		//Return: List of DataLog type
		static function getDataLogTypeList() {
			$datalog_type_list = null;
			$db = Database::get();
			$query = "SELECT * FROM " . DATALOG_TYPE_TABLE . ";";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$result = $stmt->get_result();
				while ($row = $result->fetch_assoc()) {
					$datalog_type_list[] = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for Data Log: ' . $db->error);
			}
			return $datalog_type_list;
		}
		
		//Find the datalog type name given the datalog type id
		//
		//Param: datalog type id
		//Return: datalog name (capitalized)
		static function findTypeName($id) {
			$db = Database::get();
			$name = null;
			$query = "SELECT datalog_type_name FROM " . DATALOG_TYPE_TABLE . "
					  WHERE datalog_type_id = ?;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("d", $id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$stmt->bind_result($name);
				$stmt->fetch() or $name = null;
				$stmt->close();
			} else {
				die('Invalid query for Data Log: ' . $db->error);
			}
			return ucwords($name);
		}
		
		//Add a new DataLog Type given the name
		//
		//Param: DataLog Type name
		//Return: DataLog Type ID or 0
		static function addType($name) {
			$db = Database::get();
			$query = "INSERT INTO " . DATALOG_TYPE_TABLE . " 
				(datalog_type_name) VALUES(?);";
			$stmt = $db->prepare($query);
			if ($stmt) {

				$stmt->bind_param("s", $name);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$datalog_type_id = $stmt->insert_id;
				$stmt->close();
				return intval($datalog_type_id);
			}
			return 0;
		}
		
		//Remove a DataLog Type given the id
		//
		//Param: DataLog Type ID
		//Return: true or false
		static function removeType($id) {
			$db = Database::get();
			$query = "DELETE FROM " . DATALOG_TYPE_TABLE . " 
					  WHERE datalog_type_id = ?;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("d", $id);
				$stmt->execute() or die('Invalid query for Data Log: ' . $db->error);
				$stmt->close();		
				return true;
			}
			return false;
		}
		
		//Get list of patients participating in benchmarking
		//
		//Return: List of Patients participating in benchmarking
		static function getBenchmarkPatients() {
			$patient_list = null;
			$db = Database::get();
			$query = "SELECT user_id FROM " . PATIENT_TABLE . "
					  WHERE patient_benchmark = true;";
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->execute() or die('Invalid query for Datalog: ' . $db->error);
				$result = $stmt->get_result();
				while ($row = $result->fetch_assoc()) {
					$patient_list[] = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for DataLog: ' . $db->error);
			}
			
			return $patient_list;
		}			

		//Get list of benchmarking data
		//Calculate average of user's data per day
		//Calculate average of other user's data per day and average all user's data for benchmarking
		//
		//Param: user id, type id
		//Return: List of Benchmarking data		
		static function benchmark($user_id, $datalog_type_id) {
			$benchmark_list = null;
			$db = Database::get();
			$query = "SELECT AVG(datalog_value) as datalog_average, DATE(created_at) as benchmark_date, AVG(benchmark_average) as benchmark_value FROM (
						  SELECT  " . DATALOG_TABLE . ".user_id, DATE(created_at) as datalog_date, 
						  AVG(datalog_value) as benchmark_average FROM " . DATALOG_TABLE . "	
						  INNER JOIN " . PATIENT_TABLE . "
						  ON " . DATALOG_TABLE . ".user_id = " . PATIENT_TABLE . ".user_id
						  WHERE patient_benchmark = true 
						  AND " . DATALOG_TABLE . ".user_id <> ?
						  AND datalog_type_id = ?
						  GROUP BY datalog_date, " . DATALOG_TABLE . ".user_id) AS T1
					 RIGHT JOIN " . DATALOG_TABLE . "
					 ON DATE(created_at) = T1.datalog_date
					 WHERE " . DATALOG_TABLE . ".user_id = ? AND datalog_type_id = ?
					 GROUP BY benchmark_date;";
					  
			$stmt = $db->prepare($query);
			if ($stmt) {
				$stmt->bind_param("dddd", $user_id, $datalog_type_id, $user_id, $datalog_type_id);
				$stmt->execute() or die('Invalid query for Datalog: ' . $db->error);
				$result = $stmt->get_result();

				while ($row = $result->fetch_assoc()) {
					$benchmark_list[] = $row;
				} 
				$stmt->close();
			} else {
				die('Invalid query for Datalog: ' . $db->error);
			}
			
			return $benchmark_list;
		}	
		
	}
?>